package me.firstapp.spi.bbs.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.SingleObject;
import me.firstapp.spi.base.impl.BaseServiceImpl;
import me.firstapp.spi.bbs.EmailService;

@Service
public class EmailServiceImpl extends BaseServiceImpl implements EmailService {

	@Override
	public SingleObject<Object> sendEmailCode(String email) {
		SingleObject<Object> result = new SingleObject<Object>();
		try {
			Map<String, Object> parameters = new HashMap<>();
			parameters.put("email", email);
			JSONObject resultObject = api(parameters, "/email/sendEmailCode.do", HttpMethod.POST, "发送邮箱验证码");
			if (StatusHouse.COMMON_STATUS_OK.getCode().equals(resultObject.getString("code"))) {
				result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			} else {
				throw new ServiceException(resultObject.getString("code"), resultObject.getString("msg"));
			}
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		return result;

	}

	@Override
	public SingleObject<Object> sendEmail(String email, String title, String content) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("title", title);
			params.put("content", content);

			Map<String, Object> parameters = new HashMap<>();
			parameters.put("email", email);

			JSONObject jsonObject = apiBody(parameters, "/email/sendEmail.do", "发送邮件", params);
			if (StatusHouse.COMMON_STATUS_OK.getCode().equals(jsonObject.getString("code"))) {
				result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			} else {
				throw new ServiceException(jsonObject.getString("code"), jsonObject.getString("msg"));
			}
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		return result;
	}
}
